package com.ztewatch.wearcontacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.ztewatch.wearcontacts.loader.GroupMetaDataLoader;
import com.ztewatch.wearcontacts.utils.CallUtil;
import com.ztewatch.wearcontacts.utils.ConfigLoaderSelectionUtils;
import com.ztewatch.wearcontacts.utils.ContactQuery;
import com.ztewatch.wearcontacts.view.BaseGridViewAdapter;
import com.ztewatch.wearcontacts.view.ContactCursorAdapter;
import com.ztewatch.wearcontacts.view.ScrollGridView;

public class WearContactGroupDetailActivity extends Activity {
	public static final String GROUP_DETAIL_FLAG = "group_detail_flag";
	public static final String CONTACT_READY_FLAG = "contact_ready_flag";
	public static final String GROUP_DETAIL_ID = "group_detail_id";
	private Uri groupUri;
	private long groupId;
	private ScrollGridView mDetailScrollGridView;
	private ScrollGridView base_gridview;
	private ContactCursorAdapter contactCursorAdapter;
	private List<HashMap<String, Object>> baseDataList = new ArrayList<HashMap<String, Object>>();
	private boolean isVoicecall;
	private Uri mCurLookupUri;
	private BaseGridViewAdapter baseGridViewAdapter;
	private boolean isContactReadFlag = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_group_detail);

		groupUri = getIntent().getData();
		if (groupUri != null) {
			groupId = ContentUris.parseId(groupUri);
		}
		isVoicecall = getIntent().getBooleanExtra(
				WearContactVoiceCallMainActivity.VOICE_CALL_FLAG, false);

		initView();
		initBaseGridView();
	}

	private void initView() {
		mDetailScrollGridView = (ScrollGridView) findViewById(R.id.group_detail_gridview);
		contactCursorAdapter = new ContactCursorAdapter(this, null);
		mDetailScrollGridView.setAdapter(contactCursorAdapter);
		mDetailScrollGridView
				.setOnItemClickListener(new ContactItemClickListener());
		mDetailScrollGridView.setSelected(true);
	}

	private class ContactItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Cursor cursor = (Cursor) contactCursorAdapter.getItem(position);
			if (cursor != null) {
				if (isVoicecall) {
					mCurLookupUri = getContactUri(cursor);
					if (mCurLookupUri != null) {// contact
						getLoaderManager().initLoader(2, null,
								VoicecallloaderCallbacks);
					}
				} else {
					Uri contactUri = getContactUri(cursor);
					if (contactUri != null) {// contact
						Intent intent = new Intent(
								WearContactGroupDetailActivity.this,
								WearContactDisplayActivity.class);
						intent.setData(contactUri);
						intent.putExtra(CONTACT_READY_FLAG, isContactReadFlag);
						startActivity(intent);
					}
				}
			}
		}

	}

	private final LoaderCallbacks<Cursor> VoicecallloaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			int number_type_index;
			int number_index;
			String number_type;
			String number = null;
			if (cursor != null) {
				if (!cursor.moveToFirst()) {
					cursor.close();
				} else {
					do {
						number_type_index = cursor.getColumnIndex(Data.DATA2);
						number_index = cursor.getColumnIndex(Data.DATA1);
						if (number_type_index != -1 && number_index != -1) {
							number_type = cursor.getString(number_type_index);
							if (number_type != null
									&& number_type.equals(String
											.valueOf(Phone.TYPE_MOBILE))) {
								number = cursor.getString(number_index);
								break;
							}
						}

					} while (cursor.moveToNext());
				}
			}
			if (!TextUtils.isEmpty(number)) {
				Intent intent = CallUtil.getCallIntent(number);
				startActivity(intent);
				getLoaderManager().destroyLoader(2);
			}
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			if (mCurLookupUri != null) {
				Uri uri = Uri.withAppendedPath(mCurLookupUri,
						Contacts.Entity.CONTENT_DIRECTORY);
				return new CursorLoader(WearContactGroupDetailActivity.this,
						uri, ContactQuery.VOICECALL_COLUMNS, null, null,
						Contacts.Entity.RAW_CONTACT_ID);
			} else {
				return null;
			}

		}
	};

	private final LoaderManager.LoaderCallbacks<Cursor> mGroupLoaderListener = new LoaderCallbacks<Cursor>() {

		@Override
		public CursorLoader onCreateLoader(int id, Bundle args) {
			long groupId = ContentUris.parseId(groupUri);
			return new GroupMetaDataLoader(WearContactGroupDetailActivity.this,
					groupId);
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
			if (data != null) {
				data.moveToPosition(-1);
				while (data.moveToNext()) {
					int is_read_only_index = data
							.getColumnIndex(Groups.GROUP_IS_READ_ONLY);
					if (is_read_only_index != -1) {
						int is_read_only = data.getInt(is_read_only_index);
						if (is_read_only == 1) {
							isContactReadFlag = true;
							HashMap<String, Object> hashMap = baseDataList
									.get(0);
							hashMap.put(baseGridViewAdapter.IS_DISABLE_FALG,
									true);
							HashMap<String, Object> hashMap1 = baseDataList
									.get(1);
							hashMap1.put(baseGridViewAdapter.IS_DISABLE_FALG,
									true);
							baseGridViewAdapter.notifyDataSetChanged();
						}
					}
				}

			}
		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
		}
	};

	public Uri getContactUri(Cursor cursor) {
		Uri uri = null;
		int id_index = cursor.getColumnIndex(Contacts._ID);
		int lookup_key_index = cursor.getColumnIndex(Contacts.LOOKUP_KEY);
		if (id_index != -1 && lookup_key_index != -1) {
			long contactId = cursor.getLong(id_index);
			String lookupKey = cursor.getString(lookup_key_index);
			uri = Contacts.getLookupUri(contactId, lookupKey);
		}
		return uri;
	}

	private void initBaseGridView() {
		base_gridview = (ScrollGridView) findViewById(R.id.group_detail_base_gridview);
		HashMap<String, Object> itemHashMap = new HashMap<String, Object>();
		itemHashMap.put(BaseGridViewAdapter.ITEM_IMAGE,
				R.drawable.ic_add_contact);
		itemHashMap.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_newcontact));
		baseDataList.add(itemHashMap);

		HashMap<String, Object> itemHashMap1 = new HashMap<String, Object>();
		itemHashMap1.put(BaseGridViewAdapter.ITEM_IMAGE, R.drawable.ic_edit);
		itemHashMap1.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_edit));
		baseDataList.add(itemHashMap1);

		HashMap<String, Object> itemHashMap2 = new HashMap<String, Object>();
		itemHashMap2.put(BaseGridViewAdapter.ITEM_IMAGE, R.drawable.ic_sort);
		itemHashMap2.put(BaseGridViewAdapter.ITEM_TEXT, getResources()
				.getString(R.string.base_Sort));
		baseDataList.add(itemHashMap2);

		baseGridViewAdapter = new BaseGridViewAdapter(this, baseDataList);
		base_gridview.setAdapter(baseGridViewAdapter);
		base_gridview.setOnItemClickListener(new BaseItemClickListener());
	}

	private class BaseItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:// new contact
				Intent intent = new Intent();
				intent.setAction(PasswordkeypadActivity.NEW_CONTACT_ACTION);
				intent.putExtra(GROUP_DETAIL_FLAG, true);
				intent.putExtra(GROUP_DETAIL_ID, groupId);
				if (getResources().getBoolean(R.bool.config_LGU_flag)) {
					intent.setClass(WearContactGroupDetailActivity.this,
							WearContactEditActivity.class);
				} else {
					intent.setClass(WearContactGroupDetailActivity.this,
							PasswordkeypadActivity.class);
				}
				startActivity(intent);
				break;
			case 1:// edit contact
				Intent intent1 = new Intent();
				intent1.setAction(PasswordkeypadActivity.EDIT_CONTACT_ACTION);
				intent1.putExtra(GROUP_DETAIL_FLAG, true);
				intent1.setData(groupUri);
				if (getResources().getBoolean(R.bool.config_LGU_flag)) {
					intent1.setClass(WearContactGroupDetailActivity.this,
							WearContactGroupDetailEditActivity.class);
				} else {
					intent1.setClass(WearContactGroupDetailActivity.this,
							PasswordkeypadActivity.class);
				}
				startActivity(intent1);
				break;
			case 2:// sort
				Intent intent2 = new Intent();
				// intent2.setAction(PasswordkeypadActivity.SORT_CONTACT_ACTION);
				// intent2.putExtra(GROUP_DETAIL_FLAG, true);
				intent2.setData(groupUri);
				intent2.setClass(WearContactGroupDetailActivity.this,
						WearContactGroupDetailSortActivity.class);
				startActivity(intent2);
				break;
			default:
				break;
			}
		}

	}

	private final LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {

		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
			contactCursorAdapter.swapCursor(arg1);
		}

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			CursorLoader cursorLoader = new CursorLoader(
					WearContactGroupDetailActivity.this);
			Uri uri = Contacts.CONTENT_URI;
			cursorLoader.setUri(uri);
			cursorLoader.setProjection(ContactQuery.CONTACT_PROJECTION);
			if (groupUri != null) {
				long groupId = ContentUris.parseId(groupUri);
				if (groupId > 0)
					ConfigLoaderSelectionUtils.configGroupSelection(
							cursorLoader, 0, groupId);
			}
			return cursorLoader;
		}
	};

	@Override
	protected void onStart() {
		super.onStart();
		getLoaderManager().initLoader(0, null, loaderCallbacks);
		getLoaderManager().initLoader(1, null, mGroupLoaderListener);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getLoaderManager().destroyLoader(0);
		getLoaderManager().destroyLoader(1);
	}
}
